package com.muyu.system.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.DanmoAddresses;
import com.muyu.danmo.domain.DanmoInformationBasic;
import com.muyu.danmo.domain.DanmoInformationCopy1;
import com.muyu.danmo.domain.DanmoInformationPhotos;
import com.muyu.remote.DanmoBasicService;
import com.muyu.remote.DanmoInformationCopy1Service;
import com.muyu.remote.DanmoInformationPhotosSerice;
import com.muyu.remote.RemoteAddressesService;
import com.muyu.common.core.enums.OrderStatus;
import com.muyu.system.danmo.dto.PayDTO;
import com.muyu.system.danmo.fegin.PayFeign;
import com.muyu.system.danmo.vo.PayVO;
import com.muyu.system.domain.*;
import com.muyu.system.domain.Vo.StatusCountVO;
import com.muyu.system.dto.DanmoMarketProductsDTO;
import com.muyu.system.dto.OrderStatusCountDTO;
import com.muyu.system.dto.UpdatePriceDTO;
import com.muyu.system.enums.PriceUpdateTypeEnum;
import com.muyu.system.mapper.*;
import com.muyu.system.req.DanmoMarketProductsReq;
import com.muyu.system.req.DanmoProvincesCities;
import com.muyu.system.service.IDanmoMarketProductsService;
import com.muyu.system.vo.OrderStatusCountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import static com.muyu.common.core.constant.Constants.MCH_CODE;
import static com.muyu.common.core.constant.CommonConstant.MARKET_TOP;

/**
 * 书画市场商品信息Service业务层处理
 *
 * @author yangle
 * @date 2024-09-07
 */
@Service
@Slf4j
public class DanmoMarketProductsServiceImpl implements IDanmoMarketProductsService {
    @Autowired
    private DanmoMarketProductsMapper danmoMarketProductsMapper;

    @Autowired
    private DanmoMarketOrderMapper danmoMarketOrderMapper;

    @Autowired
    private DanmoMarketPictureMapper danmoMarketPictureMapper;

    @Autowired
    private DanmoMarketSealMapper danmoMarketSealMapper;

    public DanmoMarketProductsServiceImpl() {
        System.out.println("ccc");
    }

    @Autowired
    private DanmoMarketCollectMapper danmoMarketCollectMapper;

    @Autowired
    private DanmoBasicService danmoBasicService;
    @Autowired
    private DanmoInformationCopy1Service danmoInformationCopy1Service;
    @Autowired
    private DanmoInformationPhotosSerice danmoInformationPhotosSerice;

    @Autowired
    private PayFeign payFeign;
    /**
     * 查询书画市场商品信息
     *
     * @param id 书画市场商品信息主键
     * @return 书画市场商品信息
     */
    @Override
    public DanmoMarketProducts selectDanmoMarketProductsById(Long id) {
        DanmoMarketProducts danmoMarketProducts = danmoMarketProductsMapper.selectDanmoMarketProductsById(id);
        danmoMarketProducts.setViews(danmoMarketProducts.getViews() + 1);
        danmoMarketProductsMapper.updateDanmoMarketProducts(danmoMarketProducts);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        DanmoMarketCollect danmoMarketCollect=danmoMarketCollectMapper.selectCollect(id, loginUser.getUserid());
        if (danmoMarketCollect != null){
            danmoMarketProducts.setIsCollection(String.valueOf(true));
        }else
        {
            danmoMarketProducts.setIsCollection(String.valueOf(false));
        }
        DanmoInformationBasic info = danmoBasicService.getInfoUser(danmoMarketProducts.getUserId());
        if (info != null){
            danmoMarketProducts.setDanmoInformationBasic(info);
        }
        return danmoMarketProducts;
    }

    /**
     * 查询书画市场商品信息列表
     *
     * @param danmoMarketProducts 书画市场商品信息
     * @return 书画市场商品信息
     */



    @Override
    public List<DanmoMarketProducts> selectDanmoMarketProductsList(DanmoMarketProductsDTO danmoMarketProducts) {
        danmoMarketProducts.setMarketState(1L);
        if (danmoMarketProducts.getMarketType()!=null && danmoMarketProducts.getMarketType() == 1){
            danmoMarketProducts.setMarketType(null);
        }
        List<DanmoMarketProducts> danmoMarketProductsList = danmoMarketProductsMapper.selectDanmoMarketProductsList(danmoMarketProducts);

        if (danmoMarketProducts.getMarketType()!=null && danmoMarketProducts.getMarketType() == 6 && !danmoMarketProductsList.isEmpty()){
            List<Long> longs = new ArrayList<>();
            for (DanmoMarketProducts marketProducts : danmoMarketProductsList) {
                longs.add(marketProducts.getUserId());
            }
            List<Long> informationCopy1ids = new ArrayList<>();
            List<DanmoInformationCopy1> danmoInformationCopy1List = danmoInformationCopy1Service.danmoInformationCopy1List(longs);
            for (DanmoInformationCopy1 danmoInformationCopy1 : danmoInformationCopy1List) {
                informationCopy1ids.add(danmoInformationCopy1.getId());
            }
            for (DanmoMarketProducts marketProducts : danmoMarketProductsList) {
                for (DanmoInformationCopy1 danmoInformationCopy1 : danmoInformationCopy1List) {
                    if (marketProducts.getInformationId().equals(danmoInformationCopy1.getId())){
                      marketProducts.setDanmoInformationCopy1(danmoInformationCopy1);
                    }
                }
            }
            List<DanmoInformationPhotos> danmoInformationPhotos = danmoInformationPhotosSerice.selectPhotos(informationCopy1ids);

            for (DanmoMarketProducts marketProducts : danmoMarketProductsList) {
                for (DanmoInformationPhotos danmoInformationPhotos1 : danmoInformationPhotos) {
                    if (marketProducts.getInformationId().equals(danmoInformationPhotos1.getInformationId())){
                        marketProducts.setDanmoInformationPhotos(danmoInformationPhotos1);
                    }
                }
            }
            return danmoMarketProductsList;
        }

        List<Long> longs = new ArrayList<>();
        for (DanmoMarketProducts marketProducts : danmoMarketProductsList) {
            longs.add(marketProducts.getUserId());
        }
        if(!longs.isEmpty()){
            List<DanmoInformationBasic> danmoInformationBasicList= danmoBasicService.selectUserList(longs);
            for (DanmoMarketProducts marketProducts : danmoMarketProductsList) {
                for (DanmoInformationBasic danmoInformationBasic : danmoInformationBasicList) {
                    if (marketProducts.getUserId().equals(danmoInformationBasic.getUserId())){
                        marketProducts.setDanmoInformationBasic(danmoInformationBasic);
                    }
                }
            }
        }
        return danmoMarketProductsList;

    }

    /**
     * 新增书画市场商品信息
     *
     * @param danmoMarketProducts 书画市场商品信息
     * @return 结果
     */
    @Transactional
    @Override
    public Result insertDanmoMarketProducts(DanmoMarketProducts danmoMarketProducts) {


        if (danmoMarketProducts.getDanmoMarketPictureList() == null || danmoMarketProducts.getDanmoMarketPictureList().size() == 0){
            return Result.error("请上传图片");
        }

        if (danmoMarketProducts.getPrice() == null || danmoMarketProducts.getPrice() .equals("")){
            return Result.error("请输入价格");
        }

        if (danmoMarketProducts.getProductName() == null || danmoMarketProducts.getProductName() .equals("")){
            return Result.error("请输入商品名称");
        }


//        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoMarketProducts.setCreateTime(DateUtils.getNowDate());
//        danmoMarketProducts.setCreateBy(String.valueOf(loginUser.getUserid()));
        danmoMarketProducts.setIsPosExpress("包邮");
        danmoMarketProducts.setViews(0L);

        if (danmoMarketProducts.getStatus() == 1){
//            danmoMarketProducts.setStatus(2);
            danmoMarketProducts.setStatus(1);
            danmoMarketProducts.setMarketType(Long.valueOf(6));
//            DanmoInformationCopy1 danmoInformationCopy1= danmoMarketProductsMapper.selectDanmoInfore(userid);
//            if (danmoInformationCopy1 == null){
//                return Result.error("请先上传个人信息");
//            }
//            danmoMarketProducts.setInformationId(danmoInformationCopy1.getId());
        }
        if (danmoMarketProducts.getStatus() == 2){
            if (danmoMarketProducts.getMarketType() == null ){
                return Result.error("请选择商品类型");
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userid = loginUser.getUserid();
            danmoMarketProducts.setUserId(userid);
            danmoMarketProducts.setStatus(2);
        }

        danmoMarketProducts.setMarketState(Long.valueOf(1));
        if (danmoMarketProducts.getPicture() == null){
            danmoMarketProducts.setPicture(danmoMarketProducts.getDanmoMarketPictureList().get(0).getName());
        }
        int rows = danmoMarketProductsMapper.insertDanmoMarketProducts(danmoMarketProducts);
        danmoMarketProducts.getDanmoMarketPictureList().forEach(DanmoMarketPictures -> {
            DanmoMarketPictures.setMarketId(danmoMarketProducts.getId());
            DanmoMarketPictures.setCreateTime(DateUtils.getNowDate());
//            DanmoMarketPictures.setCreateBy(String.valueOf(loginUser.getUserid()));
            danmoMarketPictureMapper.insertDanmoMarketPicture(DanmoMarketPictures);
        });
        insertDanmoMarketTypes(danmoMarketProducts);
        insertDanmoMarketSealLists(danmoMarketProducts);
        return Result.success(rows,"添加成功");
    }

    /**
     * 书画市场印章添加
     * @param danmoMarketProducts
     */
    private void insertDanmoMarketSealLists(DanmoMarketProducts danmoMarketProducts) {
        List<DanmoMarketSeal> danmoMarketSealList = danmoMarketProducts.getDanmoMarketSealList();
        Long id = danmoMarketProducts.getId();
        if (StringUtils.isNotNull(danmoMarketSealList)) {
            List<DanmoMarketSeal> list = new ArrayList<>();
            for (DanmoMarketSeal danmoMarketSeal : danmoMarketSealList) {
                danmoMarketSeal.setId(id);
                list.add(danmoMarketSeal);
            }
            if (list.size() > 0) {
                danmoMarketSealMapper.insertDanmoMarketSeals(list);
            }
        }
    }

    /**
     * 修改书画市场商品信息
     *
     * @param danmoMarketProducts 书画市场商品信息
     * @return 结果
     */
    @Transactional
    @Override
    public Result updateDanmoMarketProducts(DanmoMarketProducts danmoMarketProducts) {
        danmoMarketProducts.setUpdateTime(DateUtils.getNowDate());
        if (danmoMarketProducts.getDanmoMarketPictureList() != null) {
            danmoMarketProducts.setPicture(danmoMarketProducts.getDanmoMarketPictureList().get(0).getName());
            danmoMarketPictureMapper.deleteDanmoMarketPictureByProductId(danmoMarketProducts.getId());
            danmoMarketSealMapper.deleteDanmoMarketPictureByProductId(danmoMarketProducts.getId());
            insertDanmoMarketPictures(danmoMarketProducts);
            insertDanmoMarketSealLists(danmoMarketProducts);
        }
        UpdatePriceDTO updatePriceDTO = new UpdatePriceDTO();
        updatePriceDTO.setId(danmoMarketProducts.getId());
        updatePriceDTO.setPrice(danmoMarketProducts.getPrice());
        updatePrice(updatePriceDTO);
        return Result.success(danmoMarketProductsMapper.updateDanmoMarketProducts(danmoMarketProducts), "修改成功");
    }

    /**
     * 批量新增书画市场商品图片信息
     *
     * @param danmoMarketProducts
     */
    private void insertDanmoMarketPictures(DanmoMarketProducts danmoMarketProducts) {
        List<DanmoMarketPicture> danmoMarketTypesList = danmoMarketProducts.getDanmoMarketPictureList();
        Long id = danmoMarketProducts.getId();
        if (StringUtils.isNotNull(danmoMarketTypesList)) {
            for (DanmoMarketPicture danmoMarketPicture : danmoMarketTypesList) {
                danmoMarketPicture.setId(id);
                danmoMarketPictureMapper.insertDanmoMarketPicture(danmoMarketPicture);
            }
        }
    }

    /**
     * 批量删除书画市场商品信息
     *
     * @param ids 需要删除的书画市场商品信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public Result deleteDanmoMarketProductsByIds(Long[] ids) {
        danmoMarketPictureMapper.deleteDanmoMarketPictureByIds(ids);
        danmoMarketSealMapper.deleteDanmoMarketPictureByProductIds(ids);
        return Result.success(danmoMarketProductsMapper.deleteDanmoMarketProductsByIds(ids), "删除成功");
    }

    /**
     * 删除书画市场商品信息信息
     *
     * @param id 书画市场商品信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDanmoMarketProductsById(Long id) {
        danmoMarketProductsMapper.deleteDanmoMarketTypesById(id);
        return danmoMarketProductsMapper.deleteDanmoMarketProductsById(id);
    }


    /**
     * 新增书画市场类型信息
     *
     * @param danmoMarketProducts 书画市场商品信息对象
     */
    public void insertDanmoMarketTypes(DanmoMarketProducts danmoMarketProducts) {
        List<DanmoMarketTypes> danmoMarketTypesList = danmoMarketProducts.getDanmoMarketTypesList();
        Long id = danmoMarketProducts.getId();
        if (StringUtils.isNotNull(danmoMarketTypesList)) {
            List<DanmoMarketTypes> list = new ArrayList<DanmoMarketTypes>();
            for (DanmoMarketTypes danmoMarketTypes : danmoMarketTypesList) {
                danmoMarketTypes.setId(id);
                list.add(danmoMarketTypes);
            }
            if (list.size() > 0) {
                danmoMarketProductsMapper.batchDanmoMarketTypes(list);
            }
        }
    }


    @Override
    public Result removed(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        return Result.success(danmoMarketProductsMapper.removed(id));
    }


    @Override
    public List<DanmoMarketProducts> priceSort(DanmoMarketProducts danmoMarketProducts) {
        return danmoMarketProductsMapper.priceSort(danmoMarketProducts);
    }

    @Override
    public List<DanmoMarketProducts> selectDanmoProvincesCities(DanmoProvincesCities danmoProvincesCities) {
        return danmoMarketProductsMapper.selectDanmoProvincesCities(danmoProvincesCities);
    }

    @Override
    public List<DanmoMarketProducts> selectDanmoLatestTime(DanmoMarketProducts danmoMarketProducts) {

        return danmoMarketProductsMapper.selectDanmoLatestTime(danmoMarketProducts);
    }

    @Override
    public DanmoMarketProducts selectDanmoMarketProducts(DanmoMarketProductsReq danmoMarketProductsReq) {

        return danmoMarketProductsMapper.selectDanmoMarketProducts(danmoMarketProductsReq);
    }

    @Override
    public Result addOrder(DanmoMarketProducts danmoMarketProducts) {
        System.out.println("aa");
        return null;
    }

    @Autowired
    private RemoteAddressesService remoteAddressesService;

    @Autowired
    private DanmoMarketOrderDetailsMapper danmoMarketOrderDetailsMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result addMarket(DanmoMarketProducts danmoMarketProducts) {
        if(null == danmoMarketProducts.getPaymentMethod()){
            throw new RuntimeException("支付方式不能为空！");
        }
        if(null == danmoMarketProducts.getTel()){
            throw new RuntimeException("手机号不能为空！");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
//         获取用户地址列表
//        DanmoAddresses danmoMarketOrder = new DanmoAddresses();
//        danmoMarketOrder.setUserId(loginUser.getUserid());
        DanmoAddresses danmoAddresses = null;
        if (danmoMarketProducts.getAddressId() == null) {
            danmoAddresses = danmoMarketOrderDetailsMapper.selectByAddress(loginUser.getUserid());
        } else {
            danmoAddresses = danmoMarketOrderDetailsMapper.selectDanmoAddressesById(danmoMarketProducts.getAddressId());
        }
        Result result = remoteAddressesService.list(danmoAddresses);
        if (danmoAddresses == null) {
            return Result.error("请先添加默认地址");
        }


        // 生成订单ID
        Long id = IdWorker.getId();
        // 创建订单对象
        DanmoMarketOrder danmoMarketOrder1 = DanmoMarketOrder.builder()
                .id(id)
                .orderStatus(OrderStatus.PAY_PENDING)
                .orderSn(MARKET_TOP + RandomUtil.randomNumbers(16))
                .orderTime(DateUtils.getNowDate())
                .totalAmount(danmoMarketProducts.getCurrentPrice())
                .userId(loginUser.getUserid())
                .productId(danmoMarketProducts.getId())
                .addressesId(danmoAddresses.getId())
                .createBy(loginUser.getUsername())
                .createTime(DateUtils.getNowDate())
                .updateBy(loginUser.getUsername())
                .updateTime(DateUtils.getNowDate())
                .remark(danmoMarketProducts.getRemark())
                .shelfTime(danmoMarketProducts.getCreateTime())
                .orderSource(1L)
                .quantity(1L)
                .paymentMethod(danmoMarketProducts.getPaymentMethod())
                .totalAmount(danmoMarketProducts.getPrice())
                .sellerUserId(danmoMarketProducts.getSellerUserId())
                .receiverName(danmoAddresses.getName())
                .receiverPhone(danmoAddresses.getPhone())
                .receiverProvince(danmoAddresses.getProvinceName())
                .receiverCity(danmoAddresses.getCityName())
                .receiverRegion(danmoAddresses.getCountyName())
                .receiverDetailAddress(danmoAddresses.getAddressDetail())
                .build();


        DanmoMarketOrderDetails danmoMarketOrderDetails = DanmoMarketOrderDetails.builder()
                .orderId(id)
                .productId(danmoMarketProducts.getId())
                .quantity(1L)
                .unitPrice(danmoMarketProducts.getPrice())
                .createBy(String.valueOf(loginUser.getUserid()))
                .createTime(DateUtils.getNowDate())
                .updateBy(String.valueOf(loginUser.getUserid()))
                .updateTime(DateUtils.getNowDate())
                .buyersId(loginUser.getUserid())
                .marketState(OrderStatus.PAY_PENDING.getName())
                .addressesId(danmoAddresses.getId())
                .orderTime(DateUtils.getNowDate())
                .shelfTime(danmoMarketProducts.getCreateTime())
                .remark(danmoMarketProducts.getRemark())
                .deliveryAddress(danmoAddresses.getAddressDetail())
                .build();
        // 插入订单并返回结果
        try {
            // 调用支付
            PayDTO payDTO = new PayDTO();
            payDTO.setProjectName("书画市场");
            payDTO.setMchCode(MCH_CODE);
            payDTO.setPayMethod(danmoMarketProducts.getPaymentMethod());
            payDTO.setBizOrderNo(danmoMarketOrder1.getOrderSn());
            payDTO.setDescription("书画市场");
            payDTO.setTotalAmount(danmoMarketProducts.getPrice().multiply(BigDecimal.valueOf(100)).longValue());
            payDTO.setTimeExpire(DateUtil.offsetMinute(DateUtil.date(), 30).toLocalDateTime());
            payDTO.setPayTel(danmoMarketProducts.getTel());
            Result<PayVO> pay = payFeign.pay(payDTO);
            if(pay.getCode() != 200){
                throw  new RuntimeException(pay.getMsg());
            }
            danmoMarketOrder1.setPayOrderNo(pay.getData().getOrderNo());
            int insertResult = danmoMarketOrderMapper.insertDanmoMarketOrder(danmoMarketOrder1);
            int i = danmoMarketOrderDetailsMapper.insertDanmoMarketOrderDetails(danmoMarketOrderDetails);
            if (insertResult > 0 && i > 0) {
                DanmoMarketProducts danmoMarketProducts1 = new DanmoMarketProducts();
                danmoMarketProducts1.setId(danmoMarketProducts.getId());
                danmoMarketProducts1.setMarketState(3L);
                danmoMarketProducts1.setUpdateBy(String.valueOf(loginUser.getUserid()));
                danmoMarketProducts1.setUpdateTime(DateUtils.getNowDate());
                danmoMarketProductsMapper.updateDanmoMarketProducts(danmoMarketProducts1);
                log.info("支付系统返回的参数：{}", JSONUtil.toJsonStr(pay.getData()));
                return Result.success(pay.getData());
            } else {
                return Result.error("订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("订单创建失败: " + e.getMessage());
        }
    }

    @Override
    public DanmoMarketOrder selectSingleOrder(DanmoMarketProductsReq danmoMarketProductsReq) {
//        1.根据订单id查询出该订单
        DanmoMarketOrder danmoMarketOrder = danmoMarketOrderMapper.selectSingleOrder(danmoMarketProductsReq.getId());
        if (danmoMarketOrder == null) {
            return null;
        }
        danmoMarketOrder.setDanmoMarketProducts(danmoMarketProductsMapper.selectDanmoMarketProductsById(danmoMarketOrder.getProductId()));
        danmoMarketOrder.setDanmoAddresses(danmoMarketOrderDetailsMapper.selectDanmoAddressesById(Long.valueOf(danmoMarketOrder.getAddressesId())));
//        2.判断出该订单所绑定的用户id是否为当前用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (danmoMarketOrder.getUserId().equals(loginUser.getUserid())) {
            return danmoMarketOrder;
        }
        return null;
    }

    /**
     * 查询当前用户的商品
     *
     * @param danmoMarketProductsReq
     * @return
     */
    @Override
    public Result selectMyOrder(DanmoMarketProductsReq danmoMarketProductsReq) {
        List<DanmoMarketProducts> danmoMarketProductsList = danmoMarketProductsMapper.selectDanmoMarketProductsByUserId(danmoMarketProductsReq);
        if (danmoMarketProductsList == null) {
            return Result.error("暂无信息");
        }
        DanmoMarketProducts danmoMarketProducts = new DanmoMarketProducts();
        PageHelper.startPage(danmoMarketProducts.getPageNum(), danmoMarketProducts.getPageSize());
        PageInfo<DanmoMarketProducts> danmoMarketProductsPageInfo = new PageInfo<>(danmoMarketProductsList);
        return Result.success(danmoMarketProductsPageInfo);
    }

    @Override
    public Result selectOther(Long id) {

        return Result.success(danmoMarketProductsMapper.selectDanmoMarketProductsByUser(id));
    }

    /**
     * 他人商品
     * @param danmoMarketProductsReq
     * @return
     */
    @Override
    public Result selectOtherOrder(DanmoMarketProductsReq danmoMarketProductsReq) {
        List<DanmoMarketProducts> danmoMarketProductsList = danmoMarketProductsMapper.selectDanmoMarketProductsByOtherId(danmoMarketProductsReq);
        if (danmoMarketProductsList == null) {
            return Result.error("暂无信息");
        }
        DanmoMarketProducts danmoMarketProducts = new DanmoMarketProducts();
        PageHelper.startPage(danmoMarketProducts.getPageNum(), danmoMarketProducts.getPageSize());
        PageInfo<DanmoMarketProducts> danmoMarketProductsPageInfo = new PageInfo<>(danmoMarketProductsList);
        return Result.success(danmoMarketProductsPageInfo);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updatePrice(UpdatePriceDTO updatePriceDTO) {
        DanmoMarketProducts one = new LambdaQueryChainWrapper<>(danmoMarketProductsMapper)
                .eq(DanmoMarketProducts::getId, updatePriceDTO.getId())
                .select(DanmoMarketProducts::getPrice).one();
        BigDecimal oldPrice = one.getPrice();
        BigDecimal newPrice = updatePriceDTO.getPrice();
        PriceUpdateTypeEnum priceUpdateTypeEnum;
        if (newPrice.compareTo(oldPrice) < 0) {
            priceUpdateTypeEnum = PriceUpdateTypeEnum.CUT_PRICES;
        } else if (newPrice.compareTo(oldPrice) > 0) {
            priceUpdateTypeEnum = PriceUpdateTypeEnum.ADD_PRICES;
        } else {
            priceUpdateTypeEnum = PriceUpdateTypeEnum.NO_CHANGE;
        }
        new LambdaUpdateChainWrapper<>(danmoMarketProductsMapper)
                .eq(DanmoMarketProducts::getId, updatePriceDTO.getId())
                .set(DanmoMarketProducts::getPrice, newPrice)
                .set(DanmoMarketProducts::getCurrentPrice,  oldPrice)
                .set(DanmoMarketProducts::getPriceUpdateType, priceUpdateTypeEnum)
                .set(priceUpdateTypeEnum.equals(PriceUpdateTypeEnum.CUT_PRICES),DanmoMarketProducts::getCutPricesTime, DateUtil.date())
                .set(priceUpdateTypeEnum.equals(PriceUpdateTypeEnum.ADD_PRICES),DanmoMarketProducts::getAddPricesTime, DateUtil.date())
                .update();
    }

    @Override
    public OrderStatusCountVO orderStatusCount(OrderStatusCountDTO orderStatusCountDTO) {
        OrderStatusCountVO statusCountVO = new OrderStatusCountVO();
        List<DanmoMarketOrder> list = new LambdaQueryChainWrapper<>(danmoMarketOrderMapper)
                .eq(DanmoMarketOrder::getSellerUserId, orderStatusCountDTO.getSellerUserId())
                .isNotNull(DanmoMarketOrder::getOrderStatus)
                .select(DanmoMarketOrder::getId, DanmoMarketOrder::getOrderStatus).list();
        Map<OrderStatus, List<DanmoMarketOrder>> collect = list.stream().collect(Collectors.groupingBy(DanmoMarketOrder::getOrderStatus));
        statusCountVO.setShippedCount(collect.get(OrderStatus.TO_BE_SHIPPED) == null  ? 0 : collect.get(OrderStatus.TO_BE_SHIPPED).size());
        statusCountVO.setAfterSalesCount(collect.get(OrderStatus.AFTER_SALES) == null  ? 0 : collect.get(OrderStatus.AFTER_SALES).size());
        statusCountVO.setRejectedCount(collect.get(OrderStatus.REJECTED) == null  ? 0 : collect.get(OrderStatus.REJECTED).size());
        statusCountVO.setRefundSuccessCount(collect.get(OrderStatus.REFUND_SUCCESS) == null  ? 0 : collect.get(OrderStatus.REFUND_SUCCESS).size());
        statusCountVO.setSuccessCount(collect.get(OrderStatus.SUCCESS) == null  ? 0 : collect.get(OrderStatus.SUCCESS).size());
        return statusCountVO;
    }


    // 生成订单ID的方法
    private Long generateOrderId() {
        Random random = new Random();
        return Math.abs(random.nextLong()); // 确保生成的ID是正数
    }
}